import sys
import os
from PyQt5.QtWidgets import (
    QApplication, QMainWindow
)
from PyQt5.QtGui import QColor
from PyQt5.QtCore import Qt
from qgis.core import (
    QgsApplication,
)
from qgis.gui import (
    QgsMapCanvas,
)

from demo.layer import Layer
from demo.route import Route
from demo.status import Status
from demo.tree import Tree

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("S-57 海图查看器")
        self.resize(1600, 900)

        # 地图画布 - 白色背景
        self.canvas = QgsMapCanvas(self)
        self.canvas.setCanvasColor(QColor("white")) 
        self.setCentralWidget(self.canvas)

        # 图层树
        self.tree = Tree()
        self.addDockWidget(Qt.LeftDockWidgetArea, self.tree.get())

        # 操作状态
        self.status = Status(self.canvas)
        self.setStatusBar(self.status.get())
        # 地图加载
        self.layer = Layer(self.canvas)
        self.file_menu = self.menuBar().addMenu("文件")
        self.file_menu.addAction("打开海图", self.layer.open_file)

        # 绘制航线菜单
        self.route = Route(self.canvas)
        self.route_menu = self.menuBar().addMenu("绘制航线")
        self.route_menu.addAction("开始绘制", self.route.start_drawing)
        self.route_menu.addAction("结束绘制", self.route.exit_drawing)
        self.route_menu.addSeparator()  # 分隔线
        self.route_menu.addAction("保存航线", self.route.save_route)
        self.route_menu.addAction("清除航线", self.route.clear_route)


    def keyPressEvent(self, event):
        """处理键盘事件 - Esc键退出绘制模式"""
        if event.key() == Qt.Key_Escape and self.is_drawing:
            self.route.exit_drawing()
        else:
            super().keyPressEvent(event)


if __name__ == "__main__":
    print("启动S-57海图查看器...")
    app = QApplication(sys.argv)

    # 设置QGIS安装路径（根据实际环境修改）
    qgs = QgsApplication([], True)
    print("初始化QGIS...")
    qgs.initQgis()

    window = MainWindow()
    window.show()

    exit_code = app.exec_()
    print("退出QGIS...")
    qgs.exitQgis()
    sys.exit(exit_code)
